#include "widget.h"
#include "ui_widget.h"
#include <vector>
#include "randomthread.h"

struct WidgetPrivate
{
    std::vector<int> nums;
};

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget),p(new WidgetPrivate)
{
    ui->setupUi(this);

    //创建线程对象
    RandomThread *r = new RandomThread;
    SortThread *s = new SortThread;

    connect(ui->pushButton_Random, &QPushButton::clicked,[this,r]()
    {
        r->start();//线程启动
    });
    //跨线程通信:信号和槽不在同一个线程里,绑定方式为队列连接方式
    //connect第五个参数代表由QT自行判断采取什么连接方式
    connect(r, &RandomThread::Generate,[this](const std::vector<int>& nums)
    {
        for(auto & num : p->nums)
        {
            ui->listWidget_Random->addItem(QString::number(num));
        }
        p->nums = nums;
    });

    //线程结束信号
    connect(r, &RandomThread::finished,r,&RandomThread::deleteLater);


    connect(ui->pushButton_Sort,&QPushButton::clicked,[this,s]()
    {
        s->SetNums(p->nums);
        s->start();
    });

    connect(s,&SortThread::SortFinished,[this](const std::vector<int>& nums)
    {
        for(auto & num : p->nums)
        {
            ui->listWidget_Sort->addItem(QString::number(num));
        }
    });

    connect(s,&SortThread::finished,r,&SortThread::deleteLater);
}

Widget::~Widget()
{
    delete ui;
    delete p;
}

